// // import 'package:flutter/cupertino.dart';
// // import 'package:flutter/material.dart';
// // import 'package:flutter_inappwebview/flutter_inappwebview.dart';
// // import 'package:wch/utils/log_utils.dart';
// // import 'package:wch/widget/common_widget.dart';
// //
// // class PdfProviderPage extends StatefulWidget {
// //   const PdfProviderPage({super.key});
// //
// //   @override
// //   State<PdfProviderPage> createState() => _PdfProviderPageState();
// // }
// //
// // class _PdfProviderPageState extends State<PdfProviderPage> {
// //   @override
// //   Widget build(BuildContext context) {
// //     return CommonScaffold(title: 'pdf', body: InAppWebView(
// //       initialFile: 'assets/index.html',
// //       onWebViewCreated: (controller){
// //         LogUtils.log('onWebViewCreated');
// //         controller.addJavaScriptHandler(handlerName: 'customHandler', callback: (messageBody) {
// //           // print arguments coming from the JavaScript side!
// //           LogUtils.log('messageBody=$messageBody');
// //           // return data to the JavaScript side!
// //           return {
// //             'bar': 'bar_value', 'baz': 'baz_value'
// //           };
// //         });
// //       },
// //       onProgressChanged: (InAppWebViewController controller, int progress){
// //         LogUtils.log('pro=$progress');
// //       },
// //       shouldOverrideUrlLoading: (controller, url) async {
// //         LogUtils.log('shouldOverrideUrlLoading');
// //         return NavigationActionPolicy.ALLOW;
// //       },
// //     ));
// //   }
// // }
// import 'dart:io';
// import 'dart:typed_data';
//
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:convert' as convert;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wch/native/net_business.dart';
import 'package:wch/page/report_detail.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:path_provider/path_provider.dart';


import '../constant/resource_constant.dart';
import '../utils/loading_utils.dart';
import '../widget/padding_widget.dart';
import '../widget/text_widget.dart';

class PdfProviderPage extends StatefulWidget {
  const PdfProviderPage({super.key, required this.reportId});
  final String reportId;

  @override
  State<PdfProviderPage> createState() => _PdfProviderPageState();
}

class _PdfProviderPageState extends State<PdfProviderPage> with TickerProviderStateMixin{

  late WebViewController controller;

  AnimationController? animationController;
  Animation<double>? animation;
  ///是否已经退出当前页
  bool isExit = false;

  String? pdfPath;
  @override
  Widget build(BuildContext context) {
    return CommonScaffold(title: '报告详情', body: Container(
      child:pdfPath == null ? Container(
        child: buildRotationTransition(),
      ) : ReportDetailPage(path: pdfPath!,),
    ));
  }


  @override
  void dispose() {
    animationController?.dispose();
    isExit = true;
    super.dispose();
  }

  @override
  void initState() {
    /// 动画持续时间是 3秒，此处的this指 TickerProviderStateMixin
    animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )
      ..repeat();
    animation = Tween<double>(begin: 1, end: 0).animate(animationController!);

    initData();
  }

  void initData() async{

    Directory directory = await getTemporaryDirectory();
    String path = '${directory.path}/${widget.reportId}.pdf';
    File file = File(path);
    if (file.existsSync()) {
      setState(() {
        pdfPath = path;
      });
      return;
    }

    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {
            LogUtils.log('onPageStarted url=$url');
          },
          onPageFinished: (String url) {
            LogUtils.log('onPageFinished url=$url');
          },
          onHttpError: (HttpResponseError error) {
            LogUtils.log('onHttpError error=${error.response.toString()}');
          },
          onWebResourceError: (WebResourceError error) {
            LogUtils.log('onWebResourceError error=${error.description}');
          },
          onNavigationRequest: (NavigationRequest request) async {
            if (isExit) {
              return NavigationDecision.navigate;
            }
            LogUtils.log('request.url=${request.url}');

            if (request.url.startsWith('myapp')) {
              String decodeComponent = Uri.decodeComponent(request.url);
              LogUtils.log('decodeComponent=$decodeComponent');
              String encoded = decodeComponent.split(',')[1];
              LogUtils.log('encoded=$encoded');
              Uint8List byte = base64.decode(encoded);
              LogUtils.log('byte.len=${byte.length}');
              Directory directory = await getTemporaryDirectory();
              writeToFile(byte, '${directory.path}/${widget.reportId}.pdf');
              pdfPath = '${directory.path}/${widget.reportId}.pdf';
              setState(() {
                pdfPath;
              });

              return NavigationDecision.prevent;
            }
            return NavigationDecision.navigate;
          },
        ),
      )
      // ..addJavaScriptChannel('getDataFromApp', onMessageReceived: (onMessageReceived){
      //   LogUtils.log('getDataFromApp');
      // })
      ..loadRequest(Uri.parse('http://localhost:8080/index.html'));
    Timer(const Duration(seconds: 2), () async {
      String reportJson = await getReportData();
      if (reportJson.isNotEmpty) {
        controller.runJavaScript(reportJson);
        // controller.runJavaScript(reportJson);
      }
    });

  }

  //旋转
  Widget buildRotationTransition() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          RotationTransition(
            //设置动画的旋转中心
            alignment: Alignment.center,
            //动画控制器
            turns: animation!,
            //将要执行动画的子view
            child: Image.asset(searchLoadingIcon, width: 40.w, height: 40.w,),
          ),
          VerPadding(14.h),
          const F14TitleText('睡眠报告加载中...', color: Color(0xFF515151)),
        ],
      ),
    );
  }

  void writeToFile(Uint8List data, String path) async{
    File(path).writeAsBytes(data);
  }

  Future<String> getReportData() async{
    Map<String, dynamic> map = await NetBusiness().reportDetailStr(widget.reportId);
    String reportJson = convert.jsonEncode(map);
    // String base64String = base64Encode(utf8.encode(reportJson));
    if (reportJson.isNotEmpty) {
      reportJson = "flutterCallJsMethodNoResult(`$reportJson`)";
    }
    LogUtils.log('getReportData=$reportJson');
    return reportJson;
  }
}

